// 情感化设计交互功能实现

// 全局情感化设计管理器
class EmotionalDesignManager {
  constructor() {
    this.isFirstVisit = this.checkFirstVisit();
    this.userPreferences = this.loadUserPreferences();
    this.init();
  }

  // 初始化情感化设计
  init() {
    this.applySeasonalTheme();
    this.setupEmotionalInteractions();
    this.showWelcomeIfNeeded();
    this.setupTimeBasedGreetings();
  }

  // 检查是否是首次访问
  checkFirstVisit() {
    const visited = localStorage.getItem('demo_emotional_first_visit');
    if (!visited) {
      localStorage.setItem('demo_emotional_first_visit', 'true');
      return true;
    }
    return false;
  }

  // 加载用户偏好设置
  loadUserPreferences() {
    try {
      const prefs = localStorage.getItem('demo_emotional_preferences');
      return prefs ? JSON.parse(prefs) : {
        animations: true,
        sounds: false,
        seasonalThemes: true
      };
    } catch (error) {
      console.warn('Failed to load emotional preferences:', error);
      return {
        animations: true,
        sounds: false,
        seasonalThemes: true
      };
    }
  }

  // 保存用户偏好设置
  saveUserPreferences() {
    try {
      localStorage.setItem('demo_emotional_preferences', JSON.stringify(this.userPreferences));
    } catch (error) {
      console.warn('Failed to save emotional preferences:', error);
    }
  }

  // 应用季节主题
  applySeasonalTheme() {
    if (!this.userPreferences.seasonalThemes) return;

    const month = new Date().getMonth();
    const hour = new Date().getHours();
    
    // 移除现有主题
    document.body.classList.remove('theme-winter', 'theme-summer', 'theme-festival', 'theme-night');
    
    // 应用季节主题
    if (month >= 11 || month <= 1) {
      document.body.classList.add('theme-winter');
    } else if (month >= 5 && month <= 7) {
      document.body.classList.add('theme-summer');
    }
    
    // 应用时间主题
    if (hour >= 18 || hour <= 6) {
      document.body.classList.add('theme-night');
    }
    
    // 检查节日
    this.applyFestivalTheme();
  }

  // 应用节日主题
  applyFestivalTheme() {
    const today = new Date();
    const month = today.getMonth();
    const date = today.getDate();
    
    // 春节（农历正月初一，这里用阳历2月作为示例）
    if (month === 1 && date >= 1 && date <= 15) {
      document.body.classList.add('theme-festival');
    }
    // 圣诞节
    else if (month === 11 && date >= 20 && date <= 31) {
      document.body.classList.add('theme-festival');
    }
  }

  // 设置情感化交互
  setupEmotionalInteractions() {
    this.setupButtonEmotions();
    this.setupCardEmotions();
    this.setupFormEmotions();
    this.setupAvatarEmotions();
  }

  // 设置按钮情感化交互
  setupButtonEmotions() {
    const buttons = document.querySelectorAll('button, .btn, [role="button"]');
    
    buttons.forEach(function(button) {
      // 添加情感化类
      button.classList.add('btn-emotional', 'emotion-hover');
      
      // 点击反馈
      button.addEventListener('click', function() {
        if (this.userPreferences.animations) {
          this.classList.add('btn-click');
          setTimeout(function() {
            this.classList.remove('btn-click');
          }.bind(this), 200);
        }
        
        // 播放微妙的点击音效
        if (this.userPreferences.sounds) {
          this.playClickSound();
        }
      }.bind(this));
    }.bind(this));
  }

  // 设置卡片情感化交互
  setupCardEmotions() {
    const cards = document.querySelectorAll('.card, [role="card"], .dashboard-card');
    
    cards.forEach(function(card) {
      card.classList.add('card-emotional', 'emotion-hover');
    });
  }

  // 设置表单情感化交互
  setupFormEmotions() {
    const inputs = document.querySelectorAll('input, textarea, select');
    
    inputs.forEach(function(input) {
      input.classList.add('input-emotional');
      
      // 聚焦效果
      input.addEventListener('focus', function() {
        this.parentElement?.classList.add('focused');
      });
      
      input.addEventListener('blur', function() {
        this.parentElement?.classList.remove('focused');
      });
      
      // 输入验证反馈
      input.addEventListener('input', function() {
        if (input.validity.valid) {
          input.classList.add('valid');
          input.classList.remove('invalid');
        } else {
          input.classList.add('invalid');
          input.classList.remove('valid');
        }
      });
    });
  }

  // 设置头像情感化交互
  setupAvatarEmotions() {
    const avatars = document.querySelectorAll('.avatar, .user-avatar, [data-avatar]');
    
    avatars.forEach(function(avatar) {
      avatar.classList.add('avatar-emotional', 'emotion-hover');
    });
  }

  // 显示欢迎信息（如果是首次访问）
  showWelcomeIfNeeded() {
    if (this.isFirstVisit && this.userPreferences.animations) {
      setTimeout(function() {
        this.showWelcomeAnimation();
      }.bind(this), 1000);
    }
  }

  // 显示欢迎动画
  showWelcomeAnimation() {
    const welcomeDiv = document.createElement('div');
    welcomeDiv.className = 'welcome-confetti';
    welcomeDiv.innerHTML = `
      <div style="text-align: center; padding: 20px;">
        <div style="font-size: 3rem; margin-bottom: 10px;">🎉</div>
        <h3 style="margin: 0 0 10px 0; color: white;">欢迎使用系统管理平台！</h3>
        <p style="margin: 0; color: rgba(255,255,255,0.9); font-size: 14px;">
          发现更多精彩功能，让管理更轻松愉快
        </p>
      </div>
    `;
    
    document.body.appendChild(welcomeDiv);
    
    // 3秒后自动消失
    setTimeout(function() {
      welcomeDiv.style.opacity = '0';
      welcomeDiv.style.transform = 'translateX(-50%) scale(0.8)';
      setTimeout(function() {
        if (welcomeDiv.parentNode) {
          welcomeDiv.parentNode.removeChild(welcomeDiv);
        }
      }, 500);
    }, 3000);
  }

  // 设置时间相关的问候语
  setupTimeBasedGreetings() {
    const greetingElements = document.querySelectorAll('[data-greeting]');
    
    greetingElements.forEach(function(element) {
      const greeting = this.getTimeBasedGreeting();
      element.textContent = greeting;
      element.classList.add('greeting-emotional');
    }.bind(this));
  }

  // 获取基于时间的问候语
  getTimeBasedGreeting() {
    const hour = new Date().getHours();
    const greetings = {
      morning: ['早上好！☀️', '新的一天开始啦！🌞', '晨光正好，开始工作吧！✨'],
      afternoon: ['下午好！🌤️', '继续加油！💪', '午后时光，效率满满！🚀'],
      evening: ['晚上好！🌙', '放松一下吧！😊', '夜晚宁静，思考时刻！🌟'],
      night: ['深夜好！🌌', '注意休息哦！🛌', '夜深了，保重身体！💫']
    };
    
    let timeSlot, greetingList;
    
    if (hour < 6) {
      timeSlot = 'night';
    } else if (hour < 12) {
      timeSlot = 'morning';
    } else if (hour < 18) {
      timeSlot = 'afternoon';
    } else {
      timeSlot = 'evening';
    }
    
    greetingList = greetings[timeSlot];
    const randomIndex = Math.floor(Math.random() * greetingList.length);
    
    return greetingList[randomIndex];
  }

  // 播放点击音效
  playClickSound() {
    // 创建微妙的点击音效
    const audioContext = new (window.AudioContext || window.webkitAudioContext)();
    const oscillator = audioContext.createOscillator();
    const gainNode = audioContext.createGain();
    
    oscillator.connect(gainNode);
    gainNode.connect(audioContext.destination);
    
    oscillator.frequency.value = 800;
    oscillator.type = 'sine';
    
    gainNode.gain.setValueAtTime(0.3, audioContext.currentTime);
    gainNode.gain.exponentialRampToValueAtTime(0.01, audioContext.currentTime + 0.1);
    
    oscillator.start(audioContext.currentTime);
    oscillator.stop(audioContext.currentTime + 0.1);
  }

  // 显示成就解锁效果
  showAchievement(title, description) {
    if (!this.userPreferences.animations) return;
    
    const achievementDiv = document.createElement('div');
    achievementDiv.className = 'achievement-emotional';
    achievementDiv.style.cssText = `
      position: fixed;
      top: 20px;
      right: 20px;
      background: linear-gradient(135deg, #fbbf24, #f59e0b);
      color: white;
      padding: 15px 20px;
      border-radius: 12px;
      box-shadow: 0 8px 32px rgba(251, 191, 36, 0.4);
      z-index: 10000;
      max-width: 300px;
      animation: achievementUnlock 1.5s ease-in-out;
    `;
    
    achievementDiv.innerHTML = `
      <div style="display: flex; align-items: center; gap: 10px;">
        <span style="font-size: 1.5rem;">🏆</span>
        <div>
          <div style="font-weight: bold; font-size: 14px;">${title}</div>
          <div style="font-size: 12px; opacity: 0.9;">${description}</div>
        </div>
      </div>
    `;
    
    document.body.appendChild(achievementDiv);
    
    // 5秒后自动消失
    setTimeout(function() {
      achievementDiv.style.opacity = '0';
      achievementDiv.style.transform = 'translateX(100%)';
      setTimeout(function() {
        if (achievementDiv.parentNode) {
          achievementDiv.parentNode.removeChild(achievementDiv);
        }
      }, 500);
    }, 5000);
  }

  // 显示情感化通知
  showEmotionalNotification(message, type = 'info') {
    const notificationDiv = document.createElement('div');
    notificationDiv.className = 'notification-emotional';
    
    const typeConfig = {
      info: { color: '#3b82f6', icon: 'ℹ️' },
      success: { color: '#10b981', icon: '✅' },
      warning: { color: '#f59e0b', icon: '⚠️' },
      error: { color: '#ef4444', icon: '❌' }
    };
    
    const config = typeConfig[type] || typeConfig.info;
    
    notificationDiv.style.cssText = `
      position: fixed;
      top: 20px;
      right: 20px;
      background: white;
      color: #334155;
      padding: 15px 20px;
      border-radius: 8px;
      box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
      border-left: 4px solid ${config.color};
      z-index: 10000;
      max-width: 300px;
      animation: notificationSlide 0.5s cubic-bezier(0.34, 1.56, 0.64, 1);
    `;
    
    notificationDiv.innerHTML = `
      <div style="display: flex; align-items: center; gap: 10px;">
        <span style="font-size: 1.2rem;">${config.icon}</span>
        <div style="font-size: 14px;">${message}</div>
      </div>
    `;
    
    document.body.appendChild(notificationDiv);
    
    // 5秒后自动消失
    setTimeout(function() {
      notificationDiv.style.opacity = '0';
      notificationDiv.style.transform = 'translateX(100%)';
      setTimeout(function() {
        if (notificationDiv.parentNode) {
          notificationDiv.parentNode.removeChild(notificationDiv);
        }
      }, 500);
    }, 5000);
  }

  // 更新用户偏好
  updatePreferences(newPreferences) {
    this.userPreferences = { ...this.userPreferences, ...newPreferences };
    this.saveUserPreferences();
    
    // 根据新偏好重新应用设置
    if (newPreferences.animations !== undefined) {
      this.toggleAnimations(newPreferences.animations);
    }
    if (newPreferences.seasonalThemes !== undefined) {
      this.applySeasonalTheme();
    }
  }

  // 切换动画效果
  toggleAnimations(enabled) {
    if (enabled) {
      document.body.classList.remove('no-animations');
    } else {
      document.body.classList.add('no-animations');
    }
  }
}

// 初始化情感化设计管理器
let emotionalDesignManager;

function initEmotionalDesign() {
  emotionalDesignManager = new EmotionalDesignManager();
  
  // 将管理器暴露到全局，方便其他模块调用
  window.emotionalDesign = emotionalDesignManager;
  
  return emotionalDesignManager;
}

// 导出情感化设计功能
window.EmotionalDesign = {
  init: initEmotionalDesign,
  showAchievement: function(title, description) {
    if (emotionalDesignManager) {
      emotionalDesignManager.showAchievement(title, description);
    }
  },
  showNotification: function(message, type) {
    if (emotionalDesignManager) {
      emotionalDesignManager.showEmotionalNotification(message, type);
    }
  },
  updatePreferences: function(preferences) {
    if (emotionalDesignManager) {
      emotionalDesignManager.updatePreferences(preferences);
    }
  }
};

// 页面加载完成后初始化情感化设计
if (document.readyState === 'loading') {
  document.addEventListener('DOMContentLoaded', initEmotionalDesign);
} else {
  initEmotionalDesign();
}